package jm.mq.exceed;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import jm.mq.utils.RabbitMQUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 死信队列消费者1 接收正常状态下的消息；异常情况下发送消息到死信队列。
 * @date 2022/3/9 10:41
 */
public class Consumer1 {


    // 队列名称
    private static final String NORMAL_QUEUE = "normal_queue2";
    private static final String DEAD_QUEUE = "dead_queue2";

    // 交换机名称
    private static final String NORMAL_EXCHANGE = "e_ch2";
    private static final String DEAD_EXCHANGE = "d_ch2";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();

        // 声明队列和交换机类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);

        Map<String ,Object> arguments = new HashMap<>();
        // 设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        // 设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        // 设置最多长度，超过的进入死信
        arguments.put("x-max-length",6);

        // 创建队列
        channel.queueDeclare(NORMAL_QUEUE,false,false,false
                ,arguments);
        // 绑定RoutingKey
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");

        // 创建死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");

        System.out.println("C1等待接收消息...");

        DeliverCallback deliverCallback = (consumerTag, message) ->{
            System.out.println("C1接收到：" + new String(message.getBody(), StandardCharsets.UTF_8));
        };

        channel.basicConsume(NORMAL_QUEUE,true, deliverCallback, consumerTag ->{});
    }

}
